# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 2018-07-24
# Message: 本代码运行30个左右的pid之后,触发网站的验证码机制,解决验证码的版本是try_verifycode_bosch.py

import re
import requests
import sys
from collections import OrderedDict
import json
import time
import os
import hashlib
import pymysql
from lxml import etree

# 解决编码问题
reload(sys)
sys.setdefaultencoding('utf-8')

class Bosch_For_Pid(object):

    def __init__(self, dbconfig):
        self.base_path = '/Users/duanmengdi/Desktop/workspace/bosch_html/'  # 存储html文件的路径
        self.total_num = 0
        self.db_config = dbconfig
        self.start_url = "https://catalogue.bosch-trading.com.cn/cn/search/1?q={}"  # 搜索时拼接的url,{}=local_pid
        self.base_url = "https://catalogue.bosch-trading.com.cn/"

        # 用到的headers和postdata
        self.first_headers = {
            "Host": "catalogue.bosch-trading.com.cn",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
            "Cookie": "UM_distinctid=1648d9f06cb150-0719ad59bd385b-16386952-13c680-1648d9f06cc225; ci_session=ufjq4nb1p4hv7avh2jm1072r8eqre12d; CNZZDATA1257733696=419851453-1531383363-%7C1532396560",
        }



    def getmd5(self, str):
        md5 = hashlib.md5()
        md5.update(str)
        return md5.hexdigest()

    def get_conn(self, dbconfig_dict):
        conn = pymysql.connect(**dbconfig_dict)
        return conn

    def get_cursor(self, conn, type='stream'):
        if type == 'stream':
            return conn.cursor(pymysql.cursors.SSCursor)  # 返回流式游标,查询大量数据时不占用内存(返回数据形式是元组)
        elif type == 'dict':
            return conn.cursor(pymysql.cursors.DictCursor)  # 返回字典形式游标,查询出的数据以字典形式返回
        else:
            raise Exception("cursor type error")

    def parse_url(self, url, method, post_data=None, headers=None, tofile=True, **kwargs):
        requests.packages.urllib3.disable_warnings()  # 因为把ssl安全验证关了,所以不让代码报不安全的https请求警告
        pid = kwargs.get("local_pid", "")
        if method == 'GET':
            data = "GET" + url + pid  # 拼接data
            md5 = self.getmd5(data)  # 获取此次请求电子指纹
            file_path = self.base_path + md5 + ".html"
            if os.path.exists(file_path):  # 判断文件是否存在,如果存在就从本地读取
                print "GET for local"
                with open(file_path, 'r') as f:
                    res = f.read()
                response = res
            else:  # 如果路径不存在, 从web端请求
                print "GET for web"
                try:
                    response = requests.get(url=url, verify=False, headers=headers, timeout=30,
                                            allow_redirects=False)
                except Exception as e:
                    response = requests.get(url=url, verify=False, headers=headers, timeout=30,
                                            allow_redirects=False)

                if response:
                    if tofile:
                        with open(file_path, 'w') as f:  # 保存此次请求的html
                            f.write(response.content.decode('utf8'))
                    response = response.content.decode("utf8")
                else:
                    response = None

        elif method == "POST":
            data = "POST" + url + json.dumps(post_data)
            md5 = self.getmd5(data)
            file_path = self.base_path + md5 + ".html"
            if os.path.exists(file_path):  # 判断文件是否存在,如果存在就从本地读取
                print "POST for local"
                with open(file_path, 'r') as f:
                    res = f.read()
                response = res
            else:
                print "POST for web"
                try:
                    response = requests.post(url=url, data=post_data, verify=False, headers=headers, timeout=30,
                                             allow_redirects=False)
                except Exception as e:
                    response = requests.post(url=url, data=post_data, verify=False, headers=headers, timeout=30,
                                             allow_redirects=False)

                if response:
                    # cookies = response.cookies.get_dict()  # 可以在此获取cookies
                    # print cookies
                    if tofile:
                        with open(file_path, 'w') as f:  # 保存此次请求的html
                            f.write(response.content.decode('utf8'))
                    response = response.content.decode("utf8")

                else:
                    response = None

        return response

    def save2db(self, data_dict, curs):
        # 抽取数据
        pid = data_dict['pid'].decode('utf8')
        brand_name = data_dict['brand_name'].decode('utf8')
        part_brand = data_dict['part_brand'].decode('utf8')
        part_num = data_dict['part_num'].decode('utf8')
        part_name = data_dict['part_name'].decode('utf8')
        brand_name1 = data_dict['brand_name1'].decode('utf8')
        pid1 = data_dict['pid1'].decode('utf8')
        status = data_dict['status'].decode('utf8')

        # 拼接sql语句
        sql = '''INSERT INTO `bosch_` (`pid`, `brand_name`, `part_brand`, `part_num`, `part_name`, `brand_name1`, `pid1`, `status`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')''' % (pid, brand_name, part_brand, part_num, part_name, brand_name1, pid1, status)
        try:
            curs.execute(sql)
        except Exception as e:
            print e
            print sql
            exit()
        self.total_num += 1  # 数据总量计数

    def run(self):
        # 首先从数据库读取pid出来
        # 首先获取数据库链接和游标
        conn1 = self.get_conn(dbconfig_dict=dbconfig)
        conn2 = self.get_conn(dbconfig_dict=dbconfig)  # 用于存储
        curs1 = self.get_cursor(conn=conn1)
        curs2 = self.get_cursor(conn=conn2)  # 用于存储

        # 查询语句
        sql = u'''select brand,item,pid from 0716_pid'''
        curs1.execute(sql)
        for data in curs1:
            # time.sleep(1)  # 控制请求web的速度,防止被封,第二遍从本地请求的时候可以屏蔽
            local_pid = data[2]
            # local_pid = 'LR030778'  # 编写时测试用(能查询到数据)
            brand_name = data[0]

            # 拼接搜索请求url, 并请求
            search_url = self.start_url.format(local_pid)
            # print search_url
            search_result_response = self.parse_url(url=search_url, method="GET", headers=self.first_headers, local_pid=local_pid)
            if search_result_response:
                search_result_html = etree.HTML(search_result_response)
            else:
                raise Exception("search_result_response is None type")

            detail_url_list = search_result_html.xpath('//div[@class="info-header "]/a')

            if len(detail_url_list) <= 0:
                print "未找到详情页url列表, 跳过", local_pid
                continue

            for detail_url in detail_url_list:
                detail_url = detail_url.xpath('./@href')
                detail_url = detail_url[0] if len(detail_url)>0 else ""
                if detail_url == "":
                    print "没有找到详情页url, 跳过", local_pid
                    continue

                detail_url = "https://catalogue.bosch-trading.com.cn/cn/"+detail_url.replace("../", "")  # 修改url,不能有/../
                print detail_url

                detail_response = self.parse_url(url=detail_url, method="GET", headers=self.first_headers, local_pid=local_pid)
                if detail_response:
                    detail_html = etree.HTML(detail_response)
                else:
                    raise Exception("detail_response is None type")

                # 获取part_num, part_name
                part_info = detail_html.xpath('//div[@class="part-detail-main-info-header"]//h1/text()')
                part_info = part_info[0].split('-') if len(part_info)>0 else ""
                if part_info == "":
                    print "没有找到part_info, 跳过", local_pid
                    continue

                part_num = part_info[0].replace(" ", "").upper().replace(",", "")
                part_name = part_info[1].replace(" ", "").upper().replace(", ", "")
                # print part_name, part_num
                # exit()


                tr_list = detail_html.xpath('//div[@class="part-detail-item part-detail-oe-number"]/div[@class="part-detail-item-body"]/table/tbody/tr')
                if len(tr_list) <= 0:
                    print "没有找到OE-编号列表, 跳过", local_pid
                    continue

                # print len(tr_list)
                tr_list.pop(0)
                # print len(tr_list)

                for tr in tr_list:
                    # 获取brand_name1
                    brand_name1 = tr.xpath('./td[1]//text()')
                    brand_name1 = brand_name1[0].upper().replace(' ', '') if len(brand_name1)>0 else ""
                    if brand_name1 == "":
                        print "没有找到brand_name1, 跳过", local_pid
                    # print brand_name1

                    # 获取本品牌下的pid1列表
                    pid1_list = tr.xpath('./td[2]//a')
                    if len(pid1_list) <= 0:
                        print "本品牌下没有对应的pid1, 跳过", local_pid, brand_name1
                        continue

                    for pid1 in pid1_list:
                        pid1 = pid1.xpath('./text()')
                        pid1 = pid1[0].upper().replace(' ', '') if len(pid1)>0 else ""

                        # 过滤条件
                        if pid1 == "":
                            print "pid1 = '', 跳过", local_pid, brand_name1
                            continue
                        elif pid1 == local_pid:
                            print "pid1 = local_pid, 跳过", pid1, local_pid
                            continue
                        # print pid1

                        # 组装最后数据字典
                        last_dict = dict(
                            pid=local_pid,
                            brand_name=brand_name,
                            part_brand='bosch',  # 爬的是bosch的网站,品牌当然是bosch
                            part_num=part_num.replace('\n', ''),
                            part_name=part_name,
                            brand_name1=brand_name1,
                            pid1=pid1,
                            status=""
                        )
                        print last_dict

                        self.save2db(data_dict=last_dict, curs=curs2)

                        if self.total_num % 100 == 0:
                            conn2.commit()
                            print '>>mysql提交<<'

        conn2.commit()  # 存储数据提交
        print self.total_num
        # 关闭sql链接,释放内存
        curs1.close()
        curs2.close()
        conn1.close()
        conn2.close()


if __name__ == '__main__':
    dbconfig = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="my_data",
        charset="utf8"
    )

    tools = Bosch_For_Pid(dbconfig=dbconfig)
    tools.run()